/*
输入：m = 3, n = 5, head = [3,0,2,6,8,1,7,9,4,2,5,5,0]
输出：[[3,0,2,6,8],[5,0,-1,-1,1],[5,2,4,9,7]]
*/
class Solution {
public:
    vector<vector<int>> spiralMatrix(int m, int n, ListNode* head) 
    {
        vector<vector<int>> mat(m, vector<int>(n, -1));
        int dirs[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};  // 定义旋转方向
        int i = 0, j = 0, di = 0, dx, dy;
        while (head) {
            mat[i][j] = head -> val;
            head = head -> next; 
            dx = dirs[di][0], dy = dirs[di][1];
            if (i + dx < 0 || i + dx >= m || j + dy < 0 || j + dy >= n || mat[i + dx][j + dy] != -1) 
            {
                di = (di + 1) % 4;
                dx = dirs[di][0], dy = dirs[di][1];
            } 
            i += dx, j += dy;
        }
        return mat;
    }
};